package com.yuyou.fn.controller;

import com.google.common.collect.Maps;
import com.yuyou.fn.common.constant.SysResourceEnum;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.entity.BaseSubject;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.IBaseSubjectService;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.entity.BusTeam;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.*;
import com.yuyou.fn.platform.vo.SysResourceVo;
import com.yuyou.fn.util.Excels;
import com.yuyou.fn.util.Webs;
import com.yuyou.fn.vo.SysUserLoginSuccessVo;
import com.yuyou.fn.vo.UserConfigVo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.Collator;
import java.util.*;

/**
 * Created by wens on 2017/2/22.
 */
@Controller
@RequestMapping("/api/admin")
public class AdminCommonApiController extends ApiBaseController {

    @Resource
    private ICaptchaService captchaService;

    @Resource
    private IAccessTokenService accessTokenService;

    @Resource
    private IBusTeamService busTeamService;

    @Resource
    private IAreaTeamService areaTeamService;

    @Resource
    private ICampusService campusService;

    @Resource
    private ISysResourceService sysResourceService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private IBaseSubjectService baseSubjectService;



    @ApiOperation("登陆接口")
    @RequestMapping(value = "login", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<SysUserLoginSuccessVo> login(@RequestParam(value = "username") String username, @RequestParam("password") String password, @RequestParam(value = "captchaCode", required = false) String captchaCode, @RequestParam(value = "u", required = false) String uid, HttpSession session) {

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ReturnResult.fail("用户名和密码不能为空");
        }

        SysUser user = sysUserService.login(username, password);

        if (user == null) {
            Long failTime = captchaService.opsStat(username, "login");
            HashMap<String, Object> ret = Maps.newHashMap();
            ret.put("failTime", failTime);
            return ReturnResult.fail("用户名或密码不正确", ret);
        }


        if (user.getStatus() == 0) {
            return ReturnResult.fail("你的帐号被禁用，暂时不能登录");
        }

        if (captchaService.needVerifyCode(username, "login", 3)) {
            captchaService.verifyCode(captchaCode);
            captchaService.cleanOptStat(username ,"login");
        }

        String accessToken = accessTokenService.generateToken(user.getUserId(),user.getRealName(),"sysUser" );
        return ReturnResult.success(new SysUserLoginSuccessVo(accessToken, user));
    }


    @ApiOperation("检查登陆是否需要验证码")
    @RequestMapping(value = "/checkNeedCaptcha", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Boolean> checkNeedCaptcha(@RequestParam("username") String username) {
        Boolean ret = null;
        if (captchaService.needVerifyCode(username, "login", 3)) {
            ret = Boolean.TRUE;
        } else {
            ret = Boolean.FALSE;
        }
        return ReturnResult.success(ret);
    }

    @ApiOperation("修改自己密码")
    @RequestMapping(value = "/changeMyPassword", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> changeMyPassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword, HttpServletRequest request) {
        sysUserService.changePassword(getUserId(request), oldPassword, newPassword);
        return ReturnResult.success("OK");
    }

    @ApiOperation("检查密码状态")
    @RequestMapping(value = "/checkPasswordStatus", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Integer> checkPasswordStatus(HttpServletRequest request) {
        int status = sysUserService.checkPasswordStatus(getUserId(request));
        return ReturnResult.success(status);
    }


    @ApiOperation("获取配置(权限)")
    @RequestMapping(value = "/config", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<UserConfigVo> config(HttpServletRequest request) {

        SysUser user = getUser(request);

        DataPermission dataPermission = getDataPermission(request);

        List<SysResourceVo> resourceList = sysResourceService.findResourceByUserIdRootIdFromCache(user.getUserId(), SysResourceEnum.PC.id);

        List<Long> areaTeamIds  = dataPermission.getAreaTeamIds();
        List<Long> busTeamIds  = dataPermission.getBusTeamIds();
        List<Long> campusIds = dataPermission.getCampusIds();
        List<AreaTeam> areaTeamList = areaTeamService.findByIds(areaTeamIds);
        List<BusTeam> busTeamList = busTeamService.findByIds(busTeamIds);
        List<Campus> campusList=campusService.findByIds(campusIds);

        List<BaseGrade> gradeList = baseGradeService.findAllFromCache();
        Iterator<BaseGrade> baseGradeIterator=gradeList.iterator();
        while (baseGradeIterator.hasNext()){
            BaseGrade baseGrade=baseGradeIterator.next();
            baseGradeIterator.remove();
            gradeList.add(baseGrade);
            break;
        }

        List<BaseSubject> subjectList = baseSubjectService.findAllFromCache();
        Collections.sort(busTeamList, new Comparator<BusTeam>() {
            @Override
            public int compare(BusTeam o1, BusTeam o2) {
                return  Utils.toPinyin(o1.getName().replace("誉优","")).toLowerCase().compareTo(Utils.toPinyin(o2.getName().replace("誉优","")).toLowerCase());
            }
        });



        UserConfigVo userConfigVo = new UserConfigVo();
        userConfigVo.setUserType(user.getUserType());
        userConfigVo.setBusTeamList(busTeamList);
        userConfigVo.setAreaTeamList(areaTeamList);
        userConfigVo.setResourceList(resourceList);
        userConfigVo.setGradeList(gradeList);
        userConfigVo.setSubjectList(subjectList);
        userConfigVo.setCampusList(campusList);
        return ReturnResult.success(userConfigVo);
    }

    @ApiOperation("html转excel")
    @RequestMapping(value = "/html2excel" , method = {RequestMethod.GET, RequestMethod.POST})
    public void html2excel(@RequestParam("html") String html ,@RequestParam("downloadName") String downloadName , HttpServletRequest request , HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = Excels.fromTableOfHtml(html);
        String agent=request.getHeader("User-Agent").toLowerCase();

        Webs.writeExcel(response,workbook ,downloadName, agent);
    }
}
